package sf.view.fields;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JCheckBox;
import javax.swing.JLabel;

import sf.model.fields.BoolFieldModel;
import sf.model.fields.AbstractFieldModel;
import sf.model.fields.event.FieldChangeEvent;

public class BoolField extends AbstractField
{

	private static final long serialVersionUID = -1060951471844592743L;

	// XXX vrlo je neefikasna implementacija reakcije na promenu checkboxa
	private class BoolFieldController implements ActionListener, FocusListener
	{

		public void actionPerformed(ActionEvent e)
		{
			if (editable)
			{
				getModel().setValue(checkBox.isSelected());
			}
		}

		public void focusGained(FocusEvent e)
		{
			// TODO Auto-generated method stub

		}

		public void focusLost(FocusEvent e)
		{
			// TODO Auto-generated method stub

		}

	}

	private JCheckBox checkBox;

	private BoolFieldModel model;
	private BoolFieldController controller;

	public BoolField()
	{
		JLabel label = new JLabel(getLabelText());
		add(label, BorderLayout.WEST);

		checkBox = new JCheckBox();
		checkBox.addActionListener(controller);
		add(checkBox, BorderLayout.EAST);
		controller = new BoolFieldController();
		addFocusListener(controller);
	}

	
	public AbstractFieldModel getModel()
	{
		return model;
	}

	
	public void setModel(AbstractFieldModel model)
	{
		this.model = (BoolFieldModel) model;
		checkBox.setSelected(this.model.isSelected());
		this.model.addChangeListener(this);
	}

	
	public void changePerformed(FieldChangeEvent event)
	{
		checkBox.setSelected(((BoolFieldModel) getModel()).isSelected());
	}

	
	public Object getValue()
	{
		return model.getValue();
	}

	
	public void setValue(Object value)
	{
		model.setValue(value);
	}

	
	public void setEditable(boolean editable)
	{
		super.setEnabled(editable);
		checkBox.setEnabled(editable);
		setFocusable(editable);
	}

}
